<?php
namespace App\Http\Controllers;
include_once("httpclient.php");

class WxLogin extends Base
{


    public function logic()
    {
        //微信号
        if (!isset($this->param['wx_id'])) {
            $this->returnError(330, "wx_id must be needed");
        } else {
            $wx_id = $this->param['wx_id'];
        }

        //微信昵称
        if (!isset($this->param['nick_name'])) {
            $nick_name = "";
        } else {
            $nick_name = $this->param['nick_name'];
        }

        //微信头像URL
        if (!isset($this->param['avater_url'])) {
            $avater_url = "";
        } else {
            $avater_url = $this->param['avater_url'];
        }

        //微信性别
        if (!isset($this->param['sex'])) {
            $sex = 0;
        } else {
            $sex = $this->param['sex'];
        }

        //手机型号
        if (!isset($this->param['ua'])) {
            $ua = "";
        } else if (strlen($this->param['ua']) > 20) {
            $ua = substr($this->param['ua'], 0, 20);
        } else {
            $ua = $this->param['ua'];
        }

        $login_ip = $_SERVER["REMOTE_ADDR"];

        //该微信ID是否已经注册，如果是直接登录，如果不是注册
        $row = $this->mysql->select("t_player_info", "*", array('wx_id' => $wx_id));
        if (count($row) >= 1) {
            //该微信号已经注册过，直接登录
            if ($row[0]['status'] == 0) { //被禁号
                $this->returnError(120, "您的账号已经被管理员封禁，如有疑问请联系客服");
            }
            $uid      = $row[0]['id'];
            $now      = time();
            $datetime = date('Y-m-d H:i:s', $now);
            $skey     = md5($now);

            $province   = "未知";
            $city       = "未知";
            $url_prefix = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=";
            $url        = $url_prefix . $login_ip;
            $client     = new HttpClient();
            $ret        = $client->Get($url);
            if ($ret == false) {
            } else {
                $find = (array)json_decode($ret, true);
                if ($find["ret"] != 1) {
                } else {
                    $province = $find["province"];
                    $city     = $find["city"];
                }
            }

            $this->mysql->update("t_player_info"
                , array(
                    'login_ip' => $login_ip
                    , 'skey' => $skey
                )
                , array('id' => $uid));
            $this->mysql->insert("t_login_rec"
                , array(
                    "login_uid" => $uid
                    , 'login_type' => 2
                    , 'login_ip' => $login_ip
                    , 'login_province' => $province
                    , 'login_city' => $city
                ));

            $user_info                     = array();
            $user_info['uid']              = (int)$uid;
            $user_info['nick_name']        = $row[0]['nick_name'];
            $user_info['sex']              = (int)$row[0]['sex'];
            $user_info['avater_url']       = $row[0]['avater_url'];
            $user_info['room_ticket']      = (int)$row[0]['room_ticket'];
            $user_info['gold']             = (int)$row[0]['gold'];
            $user_info['diamonds']         = (int)$row[0]['diamonds'];
            $user_info['login_ip']         = $login_ip;
            $user_info['win_board']        = (int)$row[0]['win_board'];
            $user_info['lose_board']       = (int)$row[0]['lose_board'];
            $user_info['pin_board']        = (int)$row[0]['pin_board'];
            $user_info['skey']             = $skey;
            $user_info['login_type']       = 2;
            $user_info['paiwei_score']     = (int)$row[0]['paiwei_score'];
            $ret_arr                       = $this->cal_paiwei_rank($user_info['paiwei_score']);
            $user_info['paiwei_rank']      = $ret_arr["paiwei_rank"];
            $user_info['paiwei_rank_name'] = $ret_arr["paiwei_rank_name"];
            //每日登陆任务
            $this->add_task_unclaimed_num((int)$uid, 2);
            $this->returnData($user_info);

        } elseif (count($row) == 0) {
            //新账号，直接注册
            //随机生成user,passwd
            $array_char = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
            shuffle($array_char);
            srand(time(NULL));
            $flag = 1;
            while ($flag) {
                $users = NULL;
                for ($j = 0; $j < 4; $j++) {
                    $users = $users . $array_char[rand() % 26];
                }
                $users  = $users . rand(1000, 999999);
                $passwd = rand(100000, 999999);
                $where  = array('user' => strtolower($users));
                $row    = $this->mysql->select("t_player_info", "COUNT(*) AS `count`", $where);
                if ($row[0]['count'] >= 1) {
                } else {
                    $flag = 0;
                }
            }

            //创建用户
            $new_user = $this->createUser($ua, $wx_id, $nick_name, $avater_url, $sex, $users, $passwd);
            $uid      = $this->mysql->insert("t_player_info", $new_user);
            if ($uid == 0) {
                $this->e("insert user error");
                $this->returnError(333, "create user error,server is error.");
            }
            $datetime = date('Y-m-d H:i:s', time());

            $province   = "未知";
            $city       = "未知";
            $url_prefix = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=";
            $url        = $url_prefix . $login_ip;
            $client     = new HttpClient();
            $ret        = $client->Get($url);
            if ($ret == false) {
            } else {
                $find = (array)json_decode($ret, true);
                if ($find["ret"] != 1) {
                } else {
                    $province = $find["province"];
                    $city     = $find["city"];
                }
            }
            $this->mysql->insert("t_login_rec"
                , array(
                    "login_uid" => $uid
                    , 'login_type' => 2
                    , 'login_ip' => $login_ip
                    , 'login_province' => $province
                    , 'login_city' => $city
                ));
            $user_info                     = array();
            $user_info['uid']              = (int)$uid;
            $user_info['nick_name']        = $new_user["nick_name"];
            $user_info['sex']              = (int)$new_user['sex'];
            $user_info['avater_url']       = $new_user['avater_url'];
            $user_info['gold']             = (int)$new_user['gold'];
            $user_info['diamonds']         = (int)$new_user['diamonds'];
            $user_info['login_ip']         = $login_ip;
            $user_info['skey']             = $new_user['skey'];
            $user_info['login_type']       = 2;
            $user_info['paiwei_score']     = (int)$new_user['paiwei_score'];
            $ret_arr                       = $this->cal_paiwei_rank($user_info['paiwei_score']);
            $user_info['paiwei_rank']      = $ret_arr["paiwei_rank"];
            $user_info['paiwei_rank_name'] = $ret_arr["paiwei_rank_name"];
            //每日登陆任务
            $this->add_task_unclaimed_num((int)$uid, 2);
            $this->returnData($user_info);
        }
    }

    private function createUser($ua, $wx_id, $nick_name, $avater_url, $sex, $user, $passwd)
    {
        $now                       = date('Y-m-d H:i:s', time());
        $user_info                 = array();
        $user_info["wx_id"]        = $wx_id;
        $user_info["nick_name"]    = $nick_name;
        $user_info["passwd_md5"]   = md5($passwd);
        $user_info["passwd"]       = $passwd;
        $user_info["status"]       = 1;        // 0：为封号的, 1:表示账号可用
        $user_info["sex"]          = $sex;
        $user_info["ua"]           = $ua;
        $user_info["diamonds"]     = 88;
        $user_info["gold"]         = 15000;
        $user_info["create_time"]  = $now;
        $user_info["update_time"]  = $now;
        $user_info["skey"]         = md5(time());
        $user_info["login_ip"]     = $_SERVER["REMOTE_ADDR"];
        $user_info["paiwei_score"] = 0;
        return $user_info;
    }

    private function cal_paiwei_rank($paiwei_score)
    {
        $row = $this->mysql->find("SELECT * from t_rank_conf where $paiwei_score >= min_score AND $paiwei_score < max_score;");
        if (count($row) <= 0) {
            $this->e("get paiwei error.\n");
            $rank                     = array();
            $rank['paiwei_rank']      = 0;
            $rank['paiwei_rank_name'] = "无";
            return $rank;
        }
        $rank                     = array();
        $rank['paiwei_rank']      = (int)$row[0]["id"];
        $rank['paiwei_rank_name'] = $row[0]["name"];
        return $rank;
    }

}
